package com.bootlever.framework.zookeeper.configuration;

import com.bootlever.framework.zookeeper.properties.ZookeeperProperties;
import com.bootlever.framework.zookeeper.templates.ZookeeperTemplate;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnExpression("'${bootlever.framework.zookeeper.enbale:true}'=='true'")
public class ZookeeperConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(ZookeeperConfiguration.class);

    @Autowired
    private ZookeeperProperties zookeeperProperties;

    @Bean
    public CuratorFramework curatorFramework(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(zookeeperProperties.getSleepTimeSeconds()*1000,
                zookeeperProperties.getMaxRetries());
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString(zookeeperProperties.getNodes())
                .sessionTimeoutMs(zookeeperProperties.getSessionTimeout()).retryPolicy(retryPolicy).build();
        curatorFramework.start();
        logger.info("连接zookeeper成功");
        return curatorFramework;
    }

    @Bean
    public ZookeeperTemplate zookeeperTemplate(){
        ZookeeperTemplate zookeeperTemplate = new ZookeeperTemplate(curatorFramework());
        return zookeeperTemplate;
    }
}
